/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.catsic.security.session;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.util.Assert;

import com.catsic.base.BaseInfo;

/**
 * @description 保存用户信息(主要是IP地址)
 * @author yangyudi
 * @date 2012-9-18
 */
public class CatsicPrincipal {

	private String username;  //用户名
	private String ip;   //ip地址
	
    public CatsicPrincipal(String username, String ip) {
        Assert.notNull(username,"username cannot be null (violation of interface contract)");
        Assert.notNull(ip,"username cannot be null (violation of interface contract)");
        this.username = username;
        this.ip = ip;
    }

    public CatsicPrincipal(Authentication authentication) {
        Assert.notNull(authentication,"authentication cannot be null (violation of interface contract)");

        String username = null;
        if (authentication.getPrincipal() instanceof BaseInfo) {
            username = ((BaseInfo) authentication.getPrincipal()).getUsername();
        }else if(authentication.getPrincipal() instanceof User) {
            username = ((User) authentication.getPrincipal()).getUsername();
        }else {
            username = (String) authentication.getPrincipal().toString();
        }

        this.username = username;
    }
    
    public CatsicPrincipal(Authentication authentication, String ip) {
        Assert.notNull(authentication,"authentication cannot be null (violation of interface contract)");
        String username = null;

        if (authentication.getPrincipal() instanceof BaseInfo) {
            username = ((BaseInfo) authentication.getPrincipal()).getUsername();
        }else if(authentication.getPrincipal() instanceof User) {
            username = ((User) authentication.getPrincipal()).getUsername();
        }else {
            username = (String) authentication.getPrincipal();
        }

        //String ip = ((WebAuthenticationDetails) authentication.getDetails()).getRemoteAddress();
        this.username = username;
        this.ip = ip;
    }

    public boolean equalsIp(CatsicPrincipal smartPrincipal) {
        return this.ip.equals(smartPrincipal.ip);
    }

    @Override
    public boolean equals(Object obj) {
    	if(obj.getClass() == CatsicPrincipal.class){
    		return true;
    	}
        if (obj instanceof CatsicPrincipal) {
        	CatsicPrincipal smartPrincipal = (CatsicPrincipal) obj;
            return username.equals(smartPrincipal.username);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return username.hashCode();
    }

    @Override
    public String toString() {
        return "SmartPrincipal:{username=" + username + ",ip=" + ip + "}";
    }
    
    public void setIp(String ip){
    	this.ip = ip;
    }
}
